import allure
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from tools.get_log import GetLog
from time import sleep
log = GetLog.get_logger()


class Base:

    # 初始化 driver
    def __init__(self, driver):
        log.info("正在执行driver初始化操作")
        self.driver = driver

    # 查找
    def base_find(self, loc, timeout=10, poll=0.5):
        log.info("正在查找元素：{}".format(loc))
        # wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll)
        # return wait.until(lambda x: x.find_element(*loc))
        return self.driver.find_element(*loc)

    # 输入
    def base_input(self,  loc, value):
        el = self.base_find(loc)
        log.info("正在对：{}元素执行清空操作".format(loc))
        el.clear()
        log.info("正在对：{}元素执行 输入：{}操作".format(loc, value))
        el.send_keys(value)

    # 点击
    def base_click(self, loc):

        self.base_find(loc).click()
        log.info('正在对：{}元素执行点击操作'.format(loc))

    # 获取文本
    def base_get_text(self, loc):
        log.info('正在对:{}元素执行获取文本:{}操作'.format(loc, self.base_find(loc).text))
        return self.base_find(loc).text

    # 截图
    def base_get_image(self):
        #  调用截图方法
        log.info("正在 执行截图操作")
        self.driver.get_screenshot_as_file('./image/err.png')
        self.__base_write_report()

    # 写入报告方法
    def __base_write_report(self):
        with open('./image/err.png', 'rb') as f:
            allure.attach(f.read(), "err.png",  allure.attachment_type.PNG)

    # 点击复选框
    def base_click_element(self, title, cname):
        log.info("正在对{}元素执行点击操作".format(title))
        loc = By.CSS_SELECTOR, '[title="{}"]'.format(title)
        self.base_click(loc)
        log.info("正在对{}元素执行点击操作".format(cname))
        loc = By.CSS_SELECTOR, "[cname='{}']".format(cname)
        self.base_click(loc)

    # 品牌 型号
    def base_click_familyName(self, loc):
        self.base_click(loc)
        loc = By.XPATH, "//*[text()='标致']"
        sleep(0.5)
        self.base_click(loc)
        loc = By.XPATH, "//*[text()='东风标致207']"
        sleep(0.5)
        self.base_click(loc)
        loc = By.XPATH, "//*[text()='1.6L']"
        sleep(0.5)
        self.base_click(loc)
        loc = By.XPATH, "//*[text()='手动档']"
        sleep(0.5)
        self.base_click(loc)
        loc = By.XPATH, "//*[text()='东风标致DC7166DT轿车 2011款 三厢 手动档 驭乐版 国Ⅳ']"
        sleep(0.5)
        self.base_click(loc)

    def base_ac(self, loc):
        ac = ActionChains(self.driver)
        ac.move_to_element(
            self.base_find(loc)
        ).perform()

    def base_iframe(self, loc):
        frame = self.base_find(loc)
        self.driver.switch_to.frame(frame)
